package com.java.simple.study.juc.p3;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhoujl
 * @date 2022/5/7 20:34
 * @desc 演示局部变量线程安全问题
 */
public class ThreadSafe {

    public void method1(int loopNumber) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < loopNumber; i++) {
            // { 临界区, 会产生竞态条件
            method2(list);
            method3(list);
            // } 临界区
        }
    }

    private void method2(List<String> list) {
        list.add("1");
    }

    public void method3(List<String> list) {
        list.remove(0);
    }

    static final int THREAD_NUMBER = 2;
    static final int LOOP_NUMBER = 2000;

    public static void main(String[] args) {
        // 线程安全
        //ThreadSafe test = new ThreadSafe();
        // 线程不安全
        ThreadSafe test = new ThreadSafeSubClass();
        for (int i = 0; i < THREAD_NUMBER; i++) {
            new Thread(() -> {
                test.method1(LOOP_NUMBER);
            }, "Thread" + i).start();
        }
    }

}


class ThreadSafeSubClass extends ThreadSafe {

    @Override
    public void method3(List<String> list) {
        new Thread(() -> {
            list.remove(0);
        }).start();
    }
}
